package com.nit.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JWTUtil {
    // 设置加密秘钥
    private static final String secret = "nit";
    // 设置token过期时间: 1天
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 1;

    /**
     * 生成签名,24小时后过期
     *
     * @param seed 种子值
     * @return 加密的token
     */
    public static String sign(String seed) {
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        return JWT.create()
                .withClaim("seed", seed)
                .withClaim("seed", null == seed ? null : seed)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(secret));
    }


    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @param seed  种子值
     */
    public static boolean verify(String token, String seed) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            Map<String, Claim> claims = verifier.verify(token).getClaims();
        Claim seed_claim = claims.get("seed");
        if (seed_claim.asString().equals(seed)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的种子值
     */
    public static String getSeed(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        Map<String, Claim> claims = verifier.verify(token).getClaims();
        Claim seed_claim = claims.get("seed");
        return seed_claim.asString();
    }
}
